<?php defined('SYSPATH') or die('No direct script access.') ;

class Model_Card extends Model
{

    public function all_sql()
    {
        return DB::select('card.*', 'cat.cat_name', 'cat.unit_price')
            ->from(array('cards', 'card'))
            ->join(array('card_categories', 'cat'), 'INNER')
            ->on('cat.cat_id', '=', 'card.cat_id');
    }

    public function get($card_id)
    {
        return $this->all_sql()
            ->where('card_id', '=', $card_id)
            ->fetch_row();
    }

    public function add(array $post)
    {
        $v = Validation::factory($post)
            ->rule('cat_id', array($this, 'cat_exists'), array(':value'))
            ->rule('cards', 'not_empty')
            ->rule('cards', 'regex', array(':value', '#^[ \t]*[\w\-]+[ \t]+[\w\-]+[ \t]*(\n+[ \t]*[\w\-]+[ \t]+[\w\-]+[ \t]*)*\n*$#'));
        $this->validation($v);
        if ( ! $v->check() OR ! empty($this->_errors))
        {
            return FALSE;
        }

        $data = array();
        foreach (preg_split('#\n#', $v->cards) as $card)
        {
            if (preg_match('#^[\w\-]+\s+[\w\-]+$#', trim($card)))
            {
                 list($card_no, $card_pwd) = preg_split('#\s+#', $card);
                 $data[] = array(
                     'cat_id' => (int) $v->cat_id,
                     'card_no' => trim($card_no),
                     'card_pwd' => trim($card_pwd),
                     'create_time' => time(),
                 );
            }
        }

        foreach ($data as $val)
        {
            DB::insert('cards', $val)->execute();
        }

        // 更新库存数量
        Model::factory('card_category')->update_stock($v->cat_id);
    }

    public function del($card_id)
    {
        $card = $this->get($card_id);

        if ($card)
        {
            if ($card['fetch_time'] > 0)
            {
                return $this->error('card_id', 'fetched');
            }
            DB::delete('cards')
                ->where('card_id', '=', (int) $card_id)
                ->execute();
            Model::factory('card_category')->update_stock($card['cat_id']);
        }
    }

    public function cat_exists($cat_id)
    {
        return (bool) Model::factory('card_category')->get($cat_id);
    }

    public function stocks($cat_id)
    {
        return DB::select()
            ->from('cards')
            ->where('cat_id', '=', (int) $cat_id)
            ->where('fetch_time', '=', 0)
            ->count_all();
    }

}